import React, { useState } from 'react';
import { View, Text, TouchableOpacity, Modal, StyleSheet, Platform } from 'react-native';
import DateTimePicker from '@react-native-community/datetimepicker';
import { Ionicons } from '@expo/vector-icons';
import { Colors } from '../constants/colors';

interface Props {
  label: string;
  value?: string; // ISO string or formatted string
  onChange: (dateTimeString: string) => void;
  variant?: 'stacked' | 'card';
  mode?: 'date' | 'time' | 'datetime';
}

export default function DateTimeField({ 
  label, 
  value, 
  onChange, 
  variant = 'card',
  mode = 'datetime'
}: Props) {
  const [visible, setVisible] = useState(false);
  const [currentDate, setCurrentDate] = useState<Date>(value ? new Date(value) : new Date());
  const [pickerMode, setPickerMode] = useState<'date' | 'time'>('date');

  // 格式化显示文本
  const formatDisplayText = (date: Date): string => {
    if (mode === 'date') {
      return date.toLocaleDateString('zh-TW');
    } else if (mode === 'time') {
      return date.toLocaleTimeString('zh-TW', { hour: '2-digit', minute: '2-digit' });
    } else {
      // datetime
      return date.toLocaleString('zh-TW', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
      });
    }
  };

  // 格式化为后端需要的格式 "2025-08-21 16:00:24"
  const formatForBackend = (date: Date): string => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    
    if (mode === 'date') {
      return `${year}-${month}-${day}`;
    } else if (mode === 'time') {
      return `${hours}:${minutes}:${seconds}`;
    } else {
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }
  };

  const handleDateChange = (event: any, selectedDate?: Date) => {
    // 安卓处理逻辑
    if (Platform.OS === 'android') {
      if (event.type === 'dismissed') {
        setVisible(false);
        setPickerMode('date'); // 重置模式
        return;
      }

      if (selectedDate) {
        setCurrentDate(selectedDate);

        if (mode === 'datetime' && pickerMode === 'date') {
          // 如果是datetime模式且当前选择的是日期，接下来选择时间
          setPickerMode('time');
          // 不关闭modal，继续选择时间
        } else {
          // 完成选择
          const formattedValue = formatForBackend(selectedDate);
          onChange(formattedValue);
          setVisible(false);
          setPickerMode('date'); // 重置为日期模式
        }
      }
      return;
    }

    // iOS处理逻辑 - 只更新当前日期，不自动提交
    if (selectedDate) {
      setCurrentDate(selectedDate);
    }
  };

  const openPicker = () => {
    setPickerMode('date');
    setVisible(true);
  };

  const displayText = value ? formatDisplayText(new Date(value)) : '請選擇';

  if (variant !== 'card') {
    return (
      <View style={styles.container}>
        <Text style={styles.label}>{label}</Text>
        <TouchableOpacity style={styles.box} onPress={openPicker} activeOpacity={0.8}>
          <Text style={[styles.value, !value && styles.placeholder]}>{displayText}</Text>
          <Ionicons name="chevron-down" size={18} color={Colors.gray[400]} />
        </TouchableOpacity>

        {visible && Platform.OS === 'android' && (
          // 安卓直接显示原生选择器
          <DateTimePicker
            value={currentDate}
            onChange={handleDateChange}
            mode={pickerMode}
            display={pickerMode === 'time' ? 'clock' : 'calendar'}
            locale="zh-TW"
          />
        )}
        {visible && Platform.OS === 'ios' && (
            // iOS使用Modal包装
            <Modal
              visible={visible}
              transparent
              animationType="slide"
              onRequestClose={() => setVisible(false)}
              presentationStyle="overFullScreen"
            >
              <View style={styles.overlay}>
                <View style={styles.sheet}>
                  <Text style={styles.pickerTitle}>
                    {mode === 'datetime'
                      ? (pickerMode === 'date' ? '選擇日期' : '選擇時間')
                      : (mode === 'date' ? '選擇日期' : '選擇時間')
                    }
                  </Text>
                  <View style={styles.pickerContainer}>
                    <DateTimePicker
                      value={currentDate}
                      onChange={(_, d) => {
                        if (d) setCurrentDate(d);
                      }}
                      mode={pickerMode}
                      display="spinner"
                      textColor={Colors.black}
                      style={styles.picker}
                      locale="zh-TW"
                    />
                  </View>
                  <View style={styles.buttonRow}>
                    <TouchableOpacity style={styles.cancelBtn} onPress={() => {
                      setVisible(false);
                      setPickerMode('date');
                    }}>
                      <Text style={styles.cancelText}>取消</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.okBtn} onPress={() => {
                      if (mode === 'datetime' && pickerMode === 'date') {
                        // 如果是datetime模式且当前选择的是日期，接下来选择时间
                        setPickerMode('time');
                      } else {
                        // 完成选择
                        const formattedValue = formatForBackend(currentDate);
                        onChange(formattedValue);
                        setVisible(false);
                        setPickerMode('date');
                      }
                    }}>
                      <Text style={styles.okText}>
                        {mode === 'datetime' && pickerMode === 'date' ? '下一步' : '完成'}
                      </Text>
                    </TouchableOpacity>
                  </View>
                </View>
              </View>
            </Modal>
        )}
      </View>
    );
  }

  return (
    <View style={styles.cardContainer}>
      <View style={styles.leftRow}>
        <Text style={styles.leftLabel}>{label}</Text>
        <TouchableOpacity style={[styles.box, { flex: 1 }]} onPress={openPicker} activeOpacity={0.8}>
          <Text style={[styles.value, !value && styles.placeholder]}>{displayText}</Text>
          <Ionicons name="chevron-down" size={18} color={Colors.gray[400]} />
        </TouchableOpacity>
      </View>

      {visible && Platform.OS === 'android' && (
        // 安卓直接显示原生选择器
        <DateTimePicker
          value={currentDate}
          onChange={handleDateChange}
          mode={pickerMode}
          display={pickerMode === 'time' ? 'clock' : 'calendar'}
          locale="zh-TW"
        />
      )}
      {visible && Platform.OS === 'ios' && (
          // iOS使用Modal包装
          <Modal
            visible={visible}
            transparent
            animationType="slide"
            onRequestClose={() => setVisible(false)}
            presentationStyle="overFullScreen"
          >
            <View style={styles.overlay}>
              <View style={styles.sheet}>
                <Text style={styles.pickerTitle}>
                  {mode === 'datetime'
                    ? (pickerMode === 'date' ? '選擇日期' : '選擇時間')
                    : (mode === 'date' ? '選擇日期' : '選擇時間')
                  }
                </Text>
                <View style={styles.pickerContainer}>
                  <DateTimePicker
                    value={currentDate}
                    onChange={(_, d) => {
                      if (d) setCurrentDate(d);
                    }}
                    mode={pickerMode}
                    display="spinner"
                    textColor={Colors.black}
                    style={styles.picker}
                    locale="zh-TW"
                  />
                </View>
                <View style={styles.buttonRow}>
                  <TouchableOpacity style={styles.cancelBtn} onPress={() => {
                    setVisible(false);
                    setPickerMode('date');
                  }}>
                    <Text style={styles.cancelText}>取消</Text>
                  </TouchableOpacity>
                  <TouchableOpacity style={styles.okBtn} onPress={() => {
                    if (mode === 'datetime' && pickerMode === 'date') {
                      // 如果是datetime模式且当前选择的是日期，接下来选择时间
                      setPickerMode('time');
                    } else {
                      // 完成选择
                      const formattedValue = formatForBackend(currentDate);
                      onChange(formattedValue);
                      setVisible(false);
                      setPickerMode('date');
                    }
                  }}>
                    <Text style={styles.okText}>
                      {mode === 'datetime' && pickerMode === 'date' ? '下一步' : '完成'}
                    </Text>
                  </TouchableOpacity>
                </View>
              </View>
            </View>
          </Modal>
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: { 
    backgroundColor: Colors.gray[100], 
    borderRadius: 12, 
    paddingHorizontal: 16, 
    paddingVertical: 12 
  },
  cardContainer: {
    backgroundColor: Colors.white,
    borderRadius: 16,
    paddingHorizontal: 16,
    paddingVertical: 14,
    borderWidth: 1,
    borderColor: Colors.gray[200]
  },
  label: { 
    color: Colors.gray[400], 
    marginBottom: 6, 
    fontSize: 14 
  },
  leftRow: { 
    flexDirection: 'row', 
    alignItems: 'center' 
  },
  leftLabel: { 
    width: 88, 
    color: Colors.gray[600], 
    fontSize: 14 
  },
  box: {
    backgroundColor: Colors.white,
    borderRadius: 10,
    // 移除边框
    // borderWidth: 1,
    // borderColor: Colors.gray[200],
    paddingHorizontal: 12,
    paddingVertical: 12,
    minHeight: 44, // 确保安卓上有足够的高度
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between'
  },
  value: { 
    color: Colors.black, 
    fontSize: 16 
  },
  placeholder: { 
    color: Colors.gray[400] 
  },
  overlay: {
    flex: 1,
    backgroundColor: 'rgba(0,0,0,0.4)',
    alignItems: 'center',
    justifyContent: 'center',
  },
  sheet: {
    width: '90%',
    maxWidth: 400,
    backgroundColor: Colors.white,
    borderRadius: 16,
    padding: 20,
    alignSelf: 'center',
    elevation: 5, // 适中的安卓阴影层级
    shadowColor: '#000', // iOS阴影
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.25,
    shadowRadius: 3.84,
  },
  pickerTitle: {
    fontSize: 18,
    fontWeight: '600',
    color: Colors.gray[800],
    textAlign: 'center',
    marginBottom: 16,
  },
  pickerContainer: {
    backgroundColor: Colors.white,
    borderRadius: 8,
    marginVertical: 8,
  },
  picker: {
    backgroundColor: Colors.white,
    color: Colors.black,
  },
  buttonRow: {
    flexDirection: 'row',
    marginTop: 16,
    gap: 12,
  },
  cancelBtn: {
    flex: 1,
    backgroundColor: Colors.gray[200],
    borderRadius: 12,
    alignItems: 'center',
    paddingVertical: 10,
  },
  cancelText: {
    color: Colors.gray[700],
    fontWeight: '600',
  },
  okBtn: { 
    flex: 1,
    backgroundColor: Colors.primary, 
    borderRadius: 12, 
    alignItems: 'center', 
    paddingVertical: 10 
  },
  okText: { 
    color: Colors.white, 
    fontWeight: '700' 
  },
});
